//
//  YWEditTextController.m
//  YWPhotoEditMaster
//
//  Created by jun peng on 2023/8/15.
//

#import "YWEditTextController.h"
#import "YYText.h"

@interface YWEditTextController ()<YYTextViewDelegate>
@property (weak, nonatomic) IBOutlet YYTextView *textView;
@property (weak, nonatomic) IBOutlet UIView *colorBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *colorBgViewHeightConstraint;

- (IBAction)dismissClick:(UIButton *)sender;
- (IBAction)conformBtnClick:(UIButton *)sender;
@end

@implementation YWEditTextController

-(YWTextStatus*)currentEdittingTextStatus{
    if(_currentEdittingTextStatus == nil){
        _currentEdittingTextStatus = [[YWTextStatus alloc] init];
        
    }
    return _currentEdittingTextStatus;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    self.view.alpha = 0;
    
    [self setupUI];
    
    if(self.currentEdittingTextStatus.text != nil){
        self.textView.text = self.currentEdittingTextStatus.text;
        self.textView.textColor = self.currentEdittingTextStatus.textColor;
    }
    
    //textView
    [self setupYYTextView];
    [self.textView becomeFirstResponder];
    
    // 监听键盘的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

//销毁的时候调用
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


//---//---//--- YYTextView
-(void)setupYYTextView{
    
    self.textView.font = [UIFont systemFontOfSize:30 weight:UIFontWeightMedium];
    self.textView.textColor = self.currentEdittingTextStatus.textColor;
    self.textView.dataDetectorTypes = UIDataDetectorTypeAll;
    self.textView.placeholderText = @"编辑文字。。。";
    self.textView.placeholderTextColor = [UIColor lightGrayColor];
    self.textView.delegate = self;
    self.textView.tintColor = self.currentEdittingTextStatus.textColor;
    self.textView.backgroundColor = [UIColor clearColor];
    self.textView.returnKeyType = UIReturnKeyDefault;
    
}

/**
 *  键盘即将显示的时候调用
 */
- (void)keyboardWillShow:(NSNotification *)note
{
    // 1.取出键盘的frame
    CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 2.取出键盘弹出的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 3.执行动画
    [UIView animateWithDuration:duration animations:^{
        self.colorBgView.transform = CGAffineTransformMakeTranslation(0, -keyboardF.size.height-self.colorBgViewHeightConstraint.constant);
    }];
    
}

/**
 *  键盘即将退出的时候调用
 */
- (void)keyboardWillHide:(NSNotification *)note
{
    // 1.取出键盘弹出的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 2.执行动画
    [UIView animateWithDuration:duration animations:^{
        self.colorBgView.transform = CGAffineTransformIdentity;
    }];
    
}


//初始化UI
-(void)setupUI{
    
    NSArray *colorArray = @[[UIColor whiteColor],[UIColor cyanColor],[UIColor redColor],[UIColor yellowColor],[UIColor blueColor],[UIColor greenColor],[UIColor brownColor]];
    
    for (UIColor *color in colorArray) {
        UIButton *colorBtn = [[UIButton alloc] init];
        colorBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        colorBtn.layer.borderWidth = 2;
        colorBtn.backgroundColor = color;
        [self.colorBgView addSubview:colorBtn];
        [colorBtn addTarget:self action:@selector(colorBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    CGFloat margin = 25;
    CGFloat width = (self.colorBgView.frame.size.width - (self.colorBgView.subviews.count + 1) * margin)*1.0 / self.colorBgView.subviews.count;
    CGFloat height = width;
    CGFloat y = (self.colorBgView.frame.size.height - height)/2;
    for (NSInteger i = 0; i < self.colorBgView.subviews.count; i++) {
        UIButton *colorBtn = self.colorBgView.subviews[i];
        
        CGFloat x = margin + (width + margin) * i;
        colorBtn.frame = CGRectMake(x, y, width, height);
        colorBtn.layer.cornerRadius = height/2;
    }
    
}

-(void)colorBtnClick:(UIButton *)colorBtn{
    self.currentEdittingTextStatus.textColor = colorBtn.backgroundColor;
    
    self.textView.textColor = self.currentEdittingTextStatus.textColor;
    self.textView.tintColor = self.currentEdittingTextStatus.textColor;
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [UIView animateWithDuration:0.4 animations:^{
        self.view.alpha = 1;
    }];
}

-(void)dismiss{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.4 animations:^{
        self.view.alpha = 0;
    }completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (IBAction)dismissClick:(UIButton *)sender{
    [self dismiss];
}

- (IBAction)conformBtnClick:(UIButton *)sender{
    
    //按确定的时候才获取图片赋值
    self.currentEdittingTextStatus.image = [self getTextContentLayer];
    
    if([self.delegate respondsToSelector:@selector(editTextController:status:)]){
        [self.delegate editTextController:self status:self.currentEdittingTextStatus];
    }
    [self dismiss];
}


//获取当前图层
-(UIImage *)getTextContentLayer{

    //创建一个label装textView的内容（因为假如直接用textView的layer生成图片有可能会显示不全）
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:30 + 30 weight:UIFontWeightMedium];
    label.textColor = self.textView.textColor;
    label.numberOfLines = 0;
    label.text = self.textView.text;
    CGFloat x = self.textView.frame.origin.x;
    CGFloat y = self.textView.frame.origin.y;
    CGSize size = [label.text boundingRectWithSize:CGSizeMake(self.textView.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:label.font}  context:nil].size;
    CGFloat w = size.width;
    CGFloat h = size.height;
    label.frame = CGRectMake(x, y, w, h);
//    [self.view addSubview:label];

    //1.开启一个位图上下文
    UIGraphicsBeginImageContextWithOptions(label.frame.size, NO, 0);

    //2.把画板上的内容渲染到上下文当中
    CGContextRef ctx =  UIGraphicsGetCurrentContext();
    [label.layer renderInContext:ctx];

    //3.从上下文当中取出一张图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    //4.关闭上下文
    UIGraphicsEndImageContext();

    return newImage;
}


-(void)textViewDidChange:(YYTextView *)textView{
    
    NSLog(@"abc - %@", textView.text);
    
    self.currentEdittingTextStatus.text = textView.text;
    
}


@end
